package web.eshop.wizard;


import domain.shop.Product;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.extensions.wizard.WizardStep;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.Radio;
import org.apache.wicket.markup.html.form.RadioGroup;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.ImageService;
import service.facade.customer.ShopCustomerService;
import web.eshop.SimpleProductEshopPage;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * In this step customer select from which product want to choose components.
 */
public final class RegWizardSecondStep extends WizardStep {
    private static Logger logger = Logger.getLogger(RegWizardSecondStep.class.getName());

    @SpringBean
    private ShopCustomerService shopCustomerService;
    @SpringBean
    private ImageService imageService;

    RegWizardSecondStep(RegWizardModel regWizardModel) {
        add(new Label("choicedCarType"));
        add(new InputForm("inputForm", regWizardModel));
    }

    /**
     * form for processing the input.
     */
    private class InputForm extends Form {

        RegWizardModel regWizardModel;

        private InputForm(String id, RegWizardModel model) {
            super(id);
            this.regWizardModel = model;
            LoadableDetachableModel<List<ProductWrapper>> obj =
                    new LoadableDetachableModel<List<ProductWrapper>>() {

                        @Override
                        protected List<ProductWrapper> load() {
                            List<Product> products = shopCustomerService.getAllProductsByVehicleType(
                                    regWizardModel.getChoicedCarType());

                            List<ProductWrapper> productWrappers =
                                    new ArrayList<ProductWrapper>(products.size());

                            for (Product product : products) {
                                ProductWrapper pWrapper = new ProductWrapper(product);
                                productWrappers.add(pWrapper);
                            }
                            return productWrappers;
                        }
                    };


            RadioGroup group = new RadioGroup("group", new PropertyModel(regWizardModel, "selectedProductId"));


            ListView listView = new ListView<ProductWrapper>("productsList", obj) {

                {
                    this.setReuseItems(true);
                }

                protected void populateItem(ListItem<ProductWrapper> item) {
                    final Long productId = item.getModelObject().getProductId();

                    /*item.add(new Radio("productsSelected",
                    new PropertyModel(item, "modelObject.selected")));*/
                    item.add(new Radio("productSelected", new Model(item.getModelObject().getProductId())));

                    Link link = new Link("link") {

                        @Override
                        public void onClick() {
                            Map<String, Long> paramsMap = new HashMap<String, Long>();
                            paramsMap.put("0", productId);
                            setResponsePage(SimpleProductEshopPage.class, new PageParameters(paramsMap));
                        }
                    };

                    link.add(new Label("name", new PropertyModel(item, "modelObject.product.name")));
                    item.add(link);

                    //Image
                    boolean available = false;
                    try {
                        available = imageService.isImageAvailable(item.getModelObject().getProduct().
                                getMainImage());
                    } catch (Exception e) {
                        logger.severe("Produkt nema prirazeny obrazek");
                    }


                    Link imgLink = new Link("imgLink") {

                        @Override
                        public void onClick() {
                            Map<String, Long> paramsMap = new HashMap<String, Long>();
                            paramsMap.put("0", productId);
                            setResponsePage(SimpleProductEshopPage.class, new PageParameters(paramsMap));
                        }
                    };


                    ResourceReference ref = new ResourceReference("imageResource");
                    Long id = null;
                    try {
                        id = item.getModelObject().getProduct().getMainImage().getId();
                    } catch (Exception e) {
                        logger.severe("null in RegWizardSecondStep.java at 129");
                    }


                    String url = getRequestCycle().urlFor(ref) + "/imageEntryId/" + id;
                    //String url = "/Product/" + productId;
                    url = url + "/thumbnail/true";
                    AttributeModifier modifier = new AttributeModifier(
                            "src",
                            new Model(url));

                    /*Map<String, Long> paramsMap = new HashMap<String, Long>();
                    paramsMap.put("0", productId);
                    setResponsePage(SimpleProductEshopPage.class, new PageParameters(paramsMap));*/

                    //ExternalLink imgLink = new ExternalLink("imgLink", url);

                    Label label = new Label("thumbnailImage", "");
                    label.add(modifier);
                    label.setVisible(available);
                    imgLink.add(label);

                    label = new Label("thumbnailImageNA", "");
                    label.add(modifier);
                    label.setVisible(!available);
                    imgLink.add(label);

                    item.add(imgLink);

                }
            };
            group.add(listView);
            add(group);
        }
    }

    private class ProductWrapper implements Serializable {

        private Long productId;
        private Boolean selected = Boolean.FALSE;
        private transient Product product;

        public ProductWrapper(Product product) {
            this.productId = product.getId();
        }

        public Boolean getSelected() {
            return selected;
        }

        public void setSelected(Boolean selected) {
            this.selected = selected;
        }

        public Long getProductId() {
            return productId;
        }

        public Product getProduct() {
            if (product == null) {
                return product = shopCustomerService.findProductById(productId);
            }
            return product;
        }
    }
}
